local GuildWarPanel = app.mvc.createPanelClass(...)
local GuildWarLeftPanel = import(".GuildWarLeftPanel")
local GuildWarBottomPanel = import(".GuildWarBottomPanel")

local GuildWarFightTabPanel = import(".GuildWarFightTabPanel")
local GuildWarScheduleTabPanel = import(".GuildWarScheduleTabPanel")
local GuildWarAwardTabPanel = import(".GuildWarAwardTabPanel")
local GuildWarMemberScoreTabPanel = import(".GuildWarMemberScoreTabPanel")
local GuildWarChallengeTabPanel = import(".GuildWarChallengeTabPanel")
local CrossServerGuildWarHelper = require("app.crossServer.views.guildWar.CrossServerGuildWarHelper")
--data =
function GuildWarPanel.createWithData(data, node)
    local sprite = GuildWarPanel.extend(node or cc.CSLoader:createNode(Res.CrossServerGuildWarMain) )
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end

function GuildWarPanel.create(node)
    return GuildWarPanel.createWithData(nil, node)
end

function GuildWarPanel:init(data)
    self.super.init(self, data)
    self._leftPanel = GuildWarLeftPanel.create(self._ui["Panel/left"])
    self._bottomPanel = GuildWarBottomPanel.create(self._ui["Panel/Panel_bom"])
    self:_initContentTabs()

    self:registerViewEvent({
        {name = ViewEvent.CSGuildWar_MatchInfo, callback = handler(self, self._onGetMatchInfo)},
        {name = ViewEvent.CSGuildWar_PanelNotData, callback = handler(self, self._onUpdateNoDataTips)},
        {name = ViewEvent.Common_RedPonitChange, callback = handler(self, self._onRefreshRedPoint)},
    })
    self._curStage = nil
    self:enableNodeEvents()

    self._ui["Panel/Panel_data/Panel_top/dot_1"]:setVisible(UD.redPoint:getStateByKey(RedPointConstant.CSGuildWar_Challenge))
end

function GuildWarPanel:_onRefreshRedPoint(eventName, changeKeys)
    if changeKeys and changeKeys[RedPointConstant.CSGuildWar_Challenge] ~= nil then
        self._ui["Panel/Panel_data/Panel_top/dot_1"]:setVisible(UD.redPoint:getStateByKey(RedPointConstant.CSGuildWar_Challenge))
    end
end

function GuildWarPanel:onExit()
    self.super.onExit(self)
    self:_stopCheckTimeScheduler()
    self:_stopCheckTicketScheduler()
    self:_stopRefreshScheduler()
end

function GuildWarPanel:_onGetMatchInfo()
    self:_beginCheckTimeScheduler()
end

function GuildWarPanel:_onUpdateNoDataTips(eventName, tabIndex, content)
    if tabIndex == self._curSelectContentIndex then
        self._ui["Panel/Panel_data/Panel_tips"]:setVisible(true)
        if content then
            self._ui["Panel/Panel_data/Panel_tips/text"]:setString(content)
        end
    end
end

function GuildWarPanel:onTabSelect()
    UD.csGuildWarData:C2S_WorldGuildWarInfo()
    UD.csGuildWarData:reqLastSeaonRankData()
    UD.csGuildWarData:reqMyInGuildPowerRank()
end

function GuildWarPanel:_createContentTab(index)
    local panel = nil
    if index == 1 then
        -- 对阵
        panel = GuildWarFightTabPanel.create(self._ui["Panel/Panel_data/pvp"])
    elseif index == 2 then
        -- 赛程
        panel = GuildWarScheduleTabPanel.create(self._ui["Panel/Panel_data/ScrollView_m"])
    elseif index == 3 then
        -- 奖励
        panel = GuildWarAwardTabPanel.create(self._ui["Panel/Panel_data/ScrollView_reward"])
    elseif index == 4 then
        -- 战功
        panel = GuildWarMemberScoreTabPanel.create(self._ui["Panel/Panel_data/exploits"])
    elseif index == 5 then
        -- 挑战
        panel = GuildWarChallengeTabPanel.create(self._ui["Panel/Panel_data/challenge"])
    end
    panel:setPanelTabIndex(index)
    return panel
end

function GuildWarPanel:_initContentTabs()
    local tabConfigs = {}
    self._tabConfigs = tabConfigs

    self._curSelectContentIndex = nil
    for i = 1, 5 do
        local btn = self._ui["Panel/Panel_data/Panel_top/Button_"..i]
        local tabName = self._ui["Panel/Panel_data/Panel_top/name_"..i]
        table.insert(tabConfigs, {tab = btn, tabName = tabName, panel = self:_createContentTab(i)})

        btn:addClickEventListener(function()
            self:_onTabSelect(i)
        end)
    end
    self:_onTabSelect(1)
end

function GuildWarPanel:setSelectedByIndex(index)
    if index >= 1 and index <= 5 then
        self:_onTabSelect(index)
    end
    
end

function GuildWarPanel:_onTabSelect(index)
    if self._curSelectContentIndex == index then
        return
    end
    self._curSelectContentIndex = index
    self._ui["Panel/Panel_data/Panel_tips"]:setVisible(false)
    for i = 1, 5 do
        local config = self._tabConfigs[i]
        local panel = config.panel
        if i == index then
            config.tab:setBright(false)
            config.tabName:setOpacity(255)
            if panel.onTabSelect then
                panel:onTabSelect()
            end
            panel:setVisible(true)
        else
            config.tabName:setOpacity(255 * 0.45)
            config.tab:setBright(true)
            panel:setVisible(false)
        end
    end
end

-- 时间  驱动器
function GuildWarPanel:_getNextCheckTime()
    local startH, startM, startS = CrossServerGuildWarHelper.getGuildWarGetTicketTime()
    local ticketTime = app:getServerTimeByHMSW(startH, startM, startS, nil, false)
    local curTime = math.floor(app.session:getServerTime()) or os.time()
    if curTime < ticketTime then
        return ticketTime
    end
    --
    local startPrepareTime = tonumber(GD:getCSGuildWarPar("StartPrepareTime", "240"))
    local battlePrepareTime = tonumber(GD:getCSGuildWarPar("BattlePrepareTime", "60"))
    local startTime = ticketTime + startPrepareTime + battlePrepareTime
    if curTime < startTime then
        return startTime
    end
end

function GuildWarPanel:_beginCheckTimeScheduler()
    if self._checkTimeScheduler then
        return
    end
    local t = self:_getNextCheckTime()
    if t then
        self._checkTimeScheduler = scheduler.newCron(handler(self, self._checkTimeTick), 1, true)
        self._checkTime = t
    end
    local stage = UD.csGuildWarData:getTodayStage()
    self:_checkStageChange(stage)
end

function GuildWarPanel:_stopCheckTimeScheduler()
    if self._checkTimeScheduler then
        scheduler.cancelCron(self._checkTimeScheduler)
        self._checkTimeScheduler = nil
    end
end

-- 阶段触发 
function GuildWarPanel:_checkTimeTick()
    if not self._checkTime then
        self:_stopCheckTimeScheduler()
        return
    end
    local curTime = math.floor(app.session:getServerTime()) or os.time()
    if curTime >= self._checkTime then
        local stage = UD.csGuildWarData:getTodayStage()
        self:_checkStageChange(stage)
        self._checkTime = self:_getNextCheckTime()
        -- 停留在当前界面 当战斗开始的时候  自动进入战斗地图
        if stage == Enums.CSGuildWarTodayStage.Fighting then
            UD.csGuildWarData:C2S_EnterWorldGuildWarMap()
        end
    end
end

-- 阶段发生变化
function GuildWarPanel:_checkStageChange(stage)
    if self._curStage ~= stage then
        -- print("=============+>>> ", self._curStage, stage)
        self._curStage = stage
        if stage == Enums.CSGuildWarTodayStage.GetTicketStart then
            self:_checkTicket()
        end

        if stage == Enums.CSGuildWarTodayStage.Fighting and not UD.csGuildWarData:isCSGuildWarPrepareMap() then
            self:_refreshScore()
        end
        EM:notify(ViewEvent.CSGuildWar_StageChange, self._curStage)
    end
end

function GuildWarPanel:_checkTicket()
    local canJoin = UD.csGuildWarData:isMyGuildCanJoin()
    -- 每隔 1秒 请求 C2S_WorldGuildWarInfo 获取 参赛资格
    local stage = UD.csGuildWarData:getTodayStage()
    if canJoin and stage == Enums.CSGuildWarTodayStage.GetTicketStart then
        if not self._checkTicketSchedulerIdx then
            self._checkTicketSchedulerIdx = scheduler.newCron(handler(self, self._checkTicket), 5, true)
        else
            UD.csGuildWarData:C2S_WorldGuildWarInfo()
        end
    else
        self:_stopCheckTicketScheduler()
    end
    self:_checkStageChange(stage)
end

function GuildWarPanel:_stopCheckTicketScheduler()
    if self._checkTicketSchedulerIdx then
        scheduler.cancelCron(self._checkTicketSchedulerIdx)
        self._checkTicketSchedulerIdx = nil
    end    
end

function GuildWarPanel:_refreshScore()
    local canJoin = UD.csGuildWarData:isMyGuildCanJoin()
    -- 每隔 1秒 请求 C2S_WorldGuildWarInfo 获取 参赛资格
    local stage = UD.csGuildWarData:getTodayStage()
    if canJoin and stage == Enums.CSGuildWarTodayStage.Fighting then
        if not self._refreshScoreSchedulerIdx then
            self._refreshScoreSchedulerIdx = scheduler.newCron(handler(self, self._refreshScore), 5, true)
        else
            -- print("==============>>> _refreshScore")
            UD.csGuildWarData:C2S_WorldGuildWarInfo()
        end
    else
        self:_stopRefreshScheduler()
    end
    self:_checkStageChange(stage)
end

function GuildWarPanel:_stopRefreshScheduler()
    if self._refreshScoreSchedulerIdx then
        scheduler.cancelCron(self._refreshScoreSchedulerIdx)
        self._refreshScoreSchedulerIdx = nil
    end    
end


return GuildWarPanel